package cn.aishua.network;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import cn.aishua.ui.myKaka.task.DataExchangeAsyncTask;
import cn.aishua.ui.setting.SettingActivity;

public class UpdateAppAsyncTask
    extends DataExchangeAsyncTask
{

    // handler of main thread, used to inform main thread
    private Handler handler;

    private String strUrl;
    String mSavePath;
    String mFileName;

    private ProgressDialog downloadDialog;
    public int progress;
    private boolean cancelUpdate = false;

    public final static int DOWNLOAD = 100;
    public final static int DOWNLOAD_FINISH = 101;
    // this message is used to inform main thread
    public final static int UPDATE_DONE = 200;

    public UpdateAppAsyncTask(Context context, Handler handler)
    {
        super( context, null );
        this.handler = handler;
    }

    @Override
    protected HttpResponse sendRequest( String... params )
    {
        return HttpRequestUtil.getInstance().getApkVersion();
    }

    @Override
    protected void handleSuccResponse( String strJson ) throws Exception
    {
        // TODO this is only used to remove the extra [] which should be the error in json response
        StringBuffer sb = new StringBuffer( strJson );
        sb.deleteCharAt( 0 ).deleteCharAt( sb.length() - 1 );

        JSONObject jsonObj = new JSONObject( sb.toString() );
        String versionName = jsonObj.getString( "version" );
        int versionCode = jsonObj.getInt( "verCode" );
        strUrl = jsonObj.getString( "url" );

        if( getCurrentVersion() < versionCode ) // has new version
        {
            extractFileName();
            if( mFileName != null )
            {
                showNoticeDialog( versionName );
            }
            else
            {
                Toast.makeText( context, "服务器更新异常", Toast.LENGTH_SHORT ).show();
                informMainThread();
            }
        }
        else if( context instanceof SettingActivity ) // only promote this in Setting activity
        {
            Toast.makeText( context, "当前已是最新版本", Toast.LENGTH_SHORT ).show();
            informMainThread();
        }
        else
        {
            informMainThread();
        }
    }

    private void extractFileName()
    {
        if( strUrl != null )
        {
            String[] array = strUrl.split( "/" );
            if( array != null && array.length > 0 )
            {
                mFileName = array[array.length - 1]; // file name is the last sub string of url
            }
        }
    }

    private int getCurrentVersion() throws NameNotFoundException
    {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo = packageManager.getPackageInfo( context.getPackageName(), 0 );
        Log.d( "SettingActivity", "version name: " + packInfo.versionName );
        Log.d( "SettingActivity", "version code: " + packInfo.versionCode );
        return packInfo.versionCode;
    }

    private void showNoticeDialog( String versionName )
    {
        // build dialog
        AlertDialog.Builder builder = new Builder( context );
        builder.setTitle( "软件更新" );
        builder.setMessage( "检测到新版本" + versionName + ", 立即更新吗" );
        // button of update
        builder.setPositiveButton( "更新", new OnClickListener()
        {
            public void onClick( DialogInterface dialog, int which )
            {
                dialog.dismiss();
                // 显示下载对话框
                showDownloadDialog();
            }
        } );
        // button of cancellation
        builder.setNegativeButton( "稍后更新", new OnClickListener()
        {
            public void onClick( DialogInterface dialog, int which )
            {
                dialog.dismiss();
                informMainThread();
            }
        } );
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    /**
     * display dialog of downloading
     */
    private void showDownloadDialog()
    {
        showDialog();
        // 现在文件 
        downloadApk();
    }

    private void showDialog()
    {
        downloadDialog = new ProgressDialog( context );
        downloadDialog.setTitle( "软件更新" );
        downloadDialog.setMessage( "正在下载..." );
        downloadDialog.setMax( 100 );
        downloadDialog.setProgressStyle( ProgressDialog.STYLE_HORIZONTAL );
        downloadDialog.setButton( "取消下载", new OnClickListener()
        {

            public void onClick( DialogInterface dialog, int which )
            {
                downloadDialog.dismiss();
                cancelUpdate = true;

                informMainThread();
            }

        } );
        downloadDialog.show();
    }

    private void informMainThread()
    {
        if( handler != null )
        {
            handler.sendEmptyMessage( UPDATE_DONE );
        }
    }

    private void downloadApk()
    {
        // new thread of downloading
        new downloadApkThread().start();
    }

    private class downloadApkThread
        extends Thread
    {
        @Override
        public void run()
        {
            try
            {
                // 判断SD卡是否存在，并且是否具有读写权限 
                if( Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED ) )
                {
                    // 获得存储卡的路径 
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL( HttpRequestUtil.URL_HOST + strUrl );
                    // 创建连接 
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小 
                    int length = conn.getContentLength();
                    // 创建输入流 
                    InputStream is = conn.getInputStream();

                    File file = new File( mSavePath );
                    // 判断文件目录是否存在 
                    if( !file.exists() )
                    {
                        file.mkdir();
                    }
                    File apkFile = new File( mSavePath, mFileName );
                    FileOutputStream fos = new FileOutputStream( apkFile );
                    int count = 0;
                    // 缓存 
                    byte buf[] = new byte[1024];
                    // 写入到文件中 
                    do
                    {
                        int numread = is.read( buf );
                        count += numread;
                        // 计算进度条位置
                        progress = (int) ( ( (float) count / length ) * 100 );
                        // 更新进度
                        mHandler.sendEmptyMessage( DOWNLOAD );
                        if( numread <= 0 )
                        {
                            // 下载完成
                            mHandler.sendEmptyMessage( DOWNLOAD_FINISH );
                            break;
                        }
                        // 写入文件
                        fos.write( buf, 0, numread );
                    }
                    while( !cancelUpdate );// 点击取消就停止下载.
                    cancelUpdate = false;// revert after cancellation
                    fos.close();
                    is.close();
                }
            }
            catch( MalformedURLException e )
            {
                e.printStackTrace();
            }
            catch( IOException e )
            {
                e.printStackTrace();
            }
            // 取消下载对话框显示 
            downloadDialog.dismiss();
        }
    };

    public Handler mHandler = new Handler()
    {
        public void handleMessage( Message msg )
        {
            switch( msg.what )
            {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    downloadDialog.setProgress( progress );
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
                default:
                    break;
            }
        };
    };

    /**
     * 安装APK文件
     */
    public void installApk()
    {
        File apkfile = new File( mSavePath, mFileName );
        if( !apkfile.exists() )
        {
            return;
        }
        // 通过Intent安装APK文件 
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType( Uri.parse( "file://" + apkfile.toString() ), "application/vnd.android.package-archive" );
        context.startActivity( i );

        //        informMainThread();
    }
}
